package com.lite.ui;

import javax.swing.*;

import java.awt.event.*;

import javax.swing.event.*;

import java.awt.*;

import javax.swing.table.*;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

//import com.lite.CodeDocument;
import com.lite.Config;
import com.lite.ConnectionConfig;
import com.lite.ConnectionInformation;
import com.lite.DatabaseDialect;

import java.sql.*;
import java.text.MessageFormat;
import java.util.*;
import java.util.List;

public class MyInternalFrame extends JInternalFrame implements
		InternalFrameListener {

	/**
     * 
     */
	private static final long serialVersionUID = 9103843865329019956L;

//	class ListenerScrollBar implements AdjustmentListener {
//		public void adjustmentValueChanged(AdjustmentEvent e) {
//			if (jsb.getMaximum() != 0) {
//				System.out.println(String.valueOf(jsb.getMaximum()));
//				if ((jsb.getMaximum() - jsb.getVisibleAmount()) <= e.getValue())
//				// if ((jsb.getMaximum() - 300) <= e.getValue())
//				{
//					model.setNextResultSet(table);
//
//					setMyTableWidth();
//
//					try {
//						if (model.gResults.getRow() == 0
//								&& table.getBackground() != Color.black) {
//							statusBar.messagePane.setVisible(true);
//							statusBar.setMessagePane(model.totalRowCount
//									+ " row(s) selected.");
//						}
//					} catch (SQLException sqle) {
//						System.err.println(sqle);
//					}
//				}
//			}
//		}
//	}

	static int openFrameCount = 0;
	static final int xOffset = 30, yOffset = 30;
	// Connection connect;

	private int frameIndex = -1;
	MulitConnectionDialog argConnectionDialog;
	int commentFlag;
	String conncetionKey = null;

	Vector<Connection> connections;
	private String connectionName;
	// String dbUrl;
	int index_of_sqls = 0;
	int indexBrowseFlag = 0;

	JPanel jPanel1 = new JPanel();
	JScrollBar jsb;
	int local_index_of_sqls = 0;
	MainWindow mainFrame;
	ResultsModel model = new ResultsModel();

	String newWinUrl;
	int packageBrowseFlag = 0;
	JTextArea planArea = new JTextArea();
	int procedureBrowseFlag = 0;

	String queryWithComment;
	JTabbedPane resultTabbedPane = new JTabbedPane();

	ArrayList<String> sqls = new ArrayList<String>();

	JTextPane sqlTextArea = new JTextPane();
	Vector<Statement> statements  = new Vector<Statement>();

	StatusBar statusBar = new StatusBar();
	JTable table = new JTable(model);

	int tableBrowseFlag = 0;

	String userid;
	final UndoManager undo = new UndoManager();

	public ResultsModel getResultsModel(){
		return model;
	}
	
	public MyInternalFrame(MainWindow argMainFrame) {
		super("Document #" + (++openFrameCount), true, true, true, true);

		mainFrame = argMainFrame;

		argConnectionDialog = new MulitConnectionDialog(this);

		connections = argConnectionDialog.getConnection();
		createStatement();
		argConnectionDialog.setLocation(250, 100);
		argMainFrame.desktop.add(argConnectionDialog);
		try {
			argConnectionDialog.setSelected(true);
		} catch (java.beans.PropertyVetoException e) {
		}
		init(argMainFrame, "", "");
	}
	
	public void createStatement(){
		if ( connections == null || connections.isEmpty())
			return;
		int size = connections.size();
		try {
			Statement statement;
			Connection connection;
			for (int i = 0; i < size; i++) {
				connection = connections.get(i);
				statement = connection.createStatement();
				statements.add(statement);
			}
		} catch (SQLException sqle) {
			System.err.println(sqle); // error connection to database
			JOptionPane.showMessageDialog(this, "Can not create statement : "
					+ sqle);
		}
	}

	public MyInternalFrame(MainWindow jf, Vector<Connection> cons, String user,
			String url) {
		super("Document #" + (++openFrameCount), true, true, true, true);

		init(jf, user, url);
		this.connections = cons;
		try {
			Statement statement;
			Connection connection;
			int size = connections.size();
			for (int i = 0; i < size; i++) {
				connection = connections.get(i);
				statement = connection.createStatement();
				statements.add(statement);
			}
		} catch (SQLException sqle) {
			System.err.println(sqle); // error connection to database
			JOptionPane.showMessageDialog(this, "Can not create statement : "
					+ sqle);
		}
		pack();
		setVisible(true);
	}

	private void init(MainWindow mainFrame, String user, String url) {
		this.mainFrame = mainFrame;
		this.userid = user;
		this.newWinUrl = url;
		setConnectionName(url);

		sqlTextArea.setFont(new Font("Courier", Font.BOLD, 12));

//		CodeDocument doc = new CodeDocument();

		// undo function
//		initUndo(doc);
//		sqlTextArea.setDocument(doc);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.getViewport().add(sqlTextArea, null);

		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Use scrollbars

		JScrollPane resultsPane = new JScrollPane(table,
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); // Create
																// scrollpane
																// for table

		jsb = resultsPane.getVerticalScrollBar();

		planArea.setEditable(false);
		planArea.setFont(new Font("Default", Font.BOLD, 12));

		resultTabbedPane.addTab("ResultSet", resultsPane);

		BorderLayout bdLayout = new BorderLayout();
		jPanel1.setLayout(bdLayout);
		getContentPane().add(jPanel1, BorderLayout.CENTER);

		JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
				scrollPane, resultTabbedPane);
		jPanel1.add(splitPane, BorderLayout.CENTER);
		splitPane.setDividerLocation(150);
		getContentPane().add(splitPane, BorderLayout.CENTER);
		getContentPane().add(statusBar, BorderLayout.SOUTH);

		addInternalFrameListener(this);
		addComponentListener(new ComponentAdapter() {
			public void componentResized(ComponentEvent e) {
			}
		});
//		jsb.addAdjustmentListener(new ListenerScrollBar());

		setLocation(xOffset * openFrameCount, yOffset * openFrameCount);

		statusBar.elapsedTimePane.setVisible(false);
		statusBar.messagePane.setVisible(false);

		setPreferredSize(new java.awt.Dimension(600, 450));

		setTitle(userid.toUpperCase());

		statusBar.setUserPane(newWinUrl);

	}

	/**
	 * @param doc
	 */
//	private void initUndo(CodeDocument doc) {
//		doc.addUndoableEditListener(new UndoableEditListener() {
//			public void undoableEditHappened(UndoableEditEvent evt) {
//				undo.addEdit(evt.getEdit());
//			}
//		});
//
//		sqlTextArea.getActionMap().put("Undo", new AbstractAction("Undo") {
//			/**
//                 * 
//                 */
//			private static final long serialVersionUID = 4956600639019775601L;
//
//			public void actionPerformed(ActionEvent evt) {
//				try {
//					if (undo.canUndo()) {
//						undo.undo();
//					}
//				} catch (CannotUndoException e) {
//				}
//			}
//		});
//
//		sqlTextArea.getInputMap().put(KeyStroke.getKeyStroke("control Z"),
//				"Undo");
//
//		sqlTextArea.getActionMap().put("Redo", new AbstractAction("Redo") {
//			/**
//                 * 
//                 */
//			private static final long serialVersionUID = 237382599844729867L;
//
//			public void actionPerformed(ActionEvent evt) {
//				try {
//					if (undo.canRedo()) {
//						undo.redo();
//					}
//				} catch (CannotRedoException e) {
//				}
//			}
//		});
//
//		sqlTextArea.getInputMap().put(KeyStroke.getKeyStroke("control Y"),
//				"Redo");
//
//	}

	// public String commentHandling(String query)
	// {
	// query = query.trim();
	// int cmtAstStart = query.indexOf("/*");
	// int cmtDasStart = query.indexOf("--");
	//
	// if (cmtAstStart == 0)
	// {
	// int cmtEnd = query.indexOf("*/");
	// StringBuffer queryStrBuffer = new StringBuffer(query);
	// queryStrBuffer = queryStrBuffer.delete(cmtAstStart, cmtEnd + 2);
	// query = queryStrBuffer.toString();
	// }
	//
	// if (cmtDasStart == 0)
	// {
	// int cmtEnd = query.indexOf("\n", cmtDasStart);
	//
	// StringBuffer queryStrBuffer = new StringBuffer(query);
	// queryStrBuffer = queryStrBuffer.delete(cmtDasStart, cmtEnd - 1);
	// query = queryStrBuffer.toString();
	// }
	// return query;
	// }

	public void commitTransaction() {
		// // make sure that this connection is used with only one window.
		// // If it has more than one window ask user to confirm commit.
		//
		// try {
		// if (connection.getAutoCommit()) {
		// JOptionPane
		// .showMessageDialog(this,
		// "This connection is in auto-commit mode and cannot be committed manually.");
		// return;
		// }
		//
		// ConnectionInformation tmpConnectionInformation =
		// (ConnectionInformation) mainFrame
		// .getConnectionList().get(conncetionKey);
		// if (tmpConnectionInformation.getNumberOfWindows() > 1) {
		// int answer = JOptionPane
		// .showConfirmDialog(
		// this,
		// "This connection is being used by more than one window. \nAre you sure that you want to commit?",
		// "Warning", JOptionPane.YES_NO_OPTION,
		// JOptionPane.WARNING_MESSAGE);
		// if (answer == JOptionPane.NO_OPTION) {
		// return;
		// }
		// }
		//
		// connection.commit();
		// JOptionPane.showMessageDialog(this, "Transaction committed");
		// } catch (SQLException ex) {
		// JOptionPane.showMessageDialog(this, ex.getMessage());
		// }

	}

	public void executeDescSQL(String argQuery) {

		ConnectionInformation tmpConnectionInformation = getConnectionInformation();
		String queryDesc = tmpConnectionInformation.getDatabaseDialect()
				.getDescribeSQLString(argQuery, tmpConnectionInformation);
		if (queryDesc == null || queryDesc.equals("")) {
			// if this dialect does not support this feature must report to user
			// and exit method.
			featureNotAvailable("Describe feature", tmpConnectionInformation
					.getDatabaseDialect().getClass().getName(), this);
			return;
		}
		doHistory(argQuery);

		int color = 0;
		Statement statement = null;
		try {
			if (table.getBackground() == Color.black)
				color = 1;
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Use scrollbars
			table.setForeground(Color.black);
			table.setBackground(Color.white);
			table.setFont(new Font("Default", Font.BOLD, 12));
			table.setShowGrid(true);
			long startTime = System.currentTimeMillis();
			for (int i = 0; i < statements.size(); i++) {
				statement = statements.get(i);
				model.setResultSet(statement.executeQuery(queryDesc));
			}
			float qTime = System.currentTimeMillis() - startTime;
			qTime = qTime / 1000;

			setMyTableWidth();

			statusBar.elapsedTimePane.setVisible(true);
			statusBar.messagePane.setVisible(true);
			statusBar.setElapsedTimePane(qTime + " Sec.");
			statusBar.setMessagePane(model.getRowCount() + " row(s) selected.");
		} catch (SQLException sqle) {
			JOptionPane.showMessageDialog(this, sqle.getMessage());
			statusBar.messagePane.setVisible(true);
			statusBar.setMessagePane(sqle.getMessage()); // Display error
															// message
			if (color == 1) {
				table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
				DefaultTableColumnModel tcm = (DefaultTableColumnModel) table
						.getColumnModel();
				TableColumn tc = tcm.getColumn(0);
				table.setShowGrid(false);
				tc.setWidth(600);
				table.setForeground(Color.white);
				table.setBackground(Color.black);
				table.setFont(new Font("Default", Font.BOLD, 12));
				tc.setResizable(true);
			}
		}
	}

	// public void executePlanSQL()
	// {
	//
	// String planOut = "";
	//
	// try
	// {
	// ConnectionInformation tmpConnectionInformation =
	// getConnectionInformation();
	// planOut =
	// tmpConnectionInformation.getDatabaseDialect().doExecutePlan(sqlTextArea.getText(),tmpConnectionInformation,
	// connection);
	// if(planOut == null || planOut.equals(""))
	// {
	// //if this dialect does not support this feature must report to user and
	// exit method.
	// featureNotAvailable("Execution Plan",tmpConnectionInformation.getDatabaseDialect().getClass().getName(),this);
	// return;
	// }
	//
	// planArea.setText(planOut);
	//
	// resultTabbedPane.setSelectedIndex(1);
	// }
	// catch (SQLException sqle)
	// {
	// JOptionPane.showMessageDialog(this, sqle.getMessage());
	// sqle.printStackTrace();
	// statusBar.messagePane.setVisible(true);
	// statusBar.setMessagePane(sqle.getMessage()); // Display error message
	// }
	// }

	/**
	 * 
	 */

	public void executeSQL(String query) {

		resultTabbedPane.setSelectedIndex(0);

		doHistory(query);
		// query = commentHandling(query);

		if (query == null) // If there's nothing we are done
			return;
		int color = 0;
		Statement statement;
		Vector<ResultSet> results= new Vector<ResultSet>();
		try {
			if (table.getBackground() == Color.black)
				color = 1;
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Use scrollbars
			table.setForeground(Color.black);
			table.setBackground(Color.white);
			table.setFont(new Font("Default", Font.BOLD, 12));
			table.setShowGrid(true);
			// table.set

			sqlTextArea.setCursor(Cursor
					.getPredefinedCursor(Cursor.WAIT_CURSOR));
			this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
			long startTime = System.currentTimeMillis();
			for (int i = 0; i < statements.size(); i++) {
				statement = statements.get(i);
				results.add(statement.executeQuery(query));
			}
			model.setResultSet(results);
			float qTime = System.currentTimeMillis() - startTime;
			this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			sqlTextArea.setCursor(Cursor
					.getPredefinedCursor(Cursor.TEXT_CURSOR));

			setMyTableWidth();

			qTime = qTime / 1000;
			statusBar.elapsedTimePane.setVisible(true);
			statusBar.setElapsedTimePane(qTime + " Sec.");
			if (model.totalRowCount < 100) {
				statusBar.messagePane.setVisible(true);
				statusBar.setMessagePane(model.getRowCount()
						+ " row(s) selected.");
			} else {
				statusBar.messagePane.setVisible(false);
			}
		} catch (SQLException sqle) {
			JOptionPane.showMessageDialog(this, sqle.getMessage());
			statusBar.messagePane.setVisible(true);
			statusBar.setMessagePane(sqle.getMessage()); // Display error
															// message
			this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			sqlTextArea.setCursor(Cursor
					.getPredefinedCursor(Cursor.TEXT_CURSOR));
			if (color == 1) {
				table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
				DefaultTableColumnModel tcm = (DefaultTableColumnModel) table
						.getColumnModel();
				TableColumn tc = tcm.getColumn(0);
				table.setShowGrid(false);
				table.setCellSelectionEnabled(true);
				tc.setWidth(600);
				table.setForeground(Color.white);
				table.setBackground(Color.black);
				table.setFont(new Font("Default", Font.BOLD, 12));
				tc.setResizable(true);
			}
		}
	}

	/**
	 * @return
	 */
	public String getConncetionKey() {
		return conncetionKey;
	}

	/**
	 * @return
	 */
	public String getConnectionName() {
		return connectionName;
	}

	/**
	 * @return
	 */
	public ArrayList<String> getSqls() {
		return sqls;
	}

	public void internalFrameActivated(InternalFrameEvent e) {
		sqlTextArea.requestFocus();
	}

	public void internalFrameClosed(InternalFrameEvent e) {
		ConnectionInformation tmpConnectionInformation = getConnectionInformation();

		if (tmpConnectionInformation.getNumberOfWindows() == 1) {
			try {
				if (!connections.isEmpty()) {
					for(int i = 0; i < connections.size(); i++)
						connections.get(i).close();
				}
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} else {
			tmpConnectionInformation
					.setNumberOfWindows(tmpConnectionInformation
							.getNumberOfWindows() - 1);
			mainFrame.getConnectionList().put(conncetionKey,
					tmpConnectionInformation);
		}
		openFrameCount--;
	}

	public void internalFrameClosing(InternalFrameEvent e) {
		mainFrame.getMyInternalFrameList().remove(this);
		mainFrame.createWindowMenu();
	}

	public void internalFrameDeactivated(InternalFrameEvent e) {
	}

	public void internalFrameDeiconified(InternalFrameEvent e) {
	}

	public void internalFrameIconified(InternalFrameEvent e) {
	}

	public void internalFrameOpened(InternalFrameEvent e) {
		mainFrame.getMyInternalFrameList().add(this);
		mainFrame.createWindowMenu();
		sqlTextArea.transferFocus();
	}

	public void prexecuteSQL() {
		DatabaseDialect tmpDatabaseDialect = getConnectionInformation()
				.getDatabaseDialect();

		String query = sqlTextArea.getSelectedText();
		if (query == null || query.length() <= 0) {
			query = sqlTextArea.getText();
		}

		// query = commentHandling(query);

		query = query.trim();

		if (tmpDatabaseDialect.isSelectStatement(query)) {
			executeSQL(query);
		} else if (tmpDatabaseDialect.isDescribeStatement(query)) {
			executeDescSQL(query);
		} else if (query.equalsIgnoreCase("COMMIT")) {
			commitTransaction();
		} else if (query.equalsIgnoreCase("ROLLBACK")) {
			rollBackTransaction();
		} else {
			updateSQL(query);
		}
	}

	public void rollBackTransaction() {
		// // make sure that this connection is used with only one window.
		// // If it has more than one window ask user to confirm rollback.
		//
		// try {
		// if (connection.getAutoCommit()) {
		// JOptionPane
		// .showMessageDialog(this,
		// "This connection is in auto-commit mode and cannot be rolled back.");
		// return;
		// }
		//
		// ConnectionInformation tmpConnectionInformation =
		// (ConnectionInformation) mainFrame
		// .getConnectionList().get(conncetionKey);
		// if (tmpConnectionInformation.getNumberOfWindows() > 1) {
		// int answer = JOptionPane
		// .showConfirmDialog(
		// this,
		// "This connection is being used by more than one window. \nAre you sure that you want to rollback?",
		// "Warning", JOptionPane.YES_NO_OPTION,
		// JOptionPane.WARNING_MESSAGE);
		// if (answer == JOptionPane.NO_OPTION) {
		// return;
		// }
		// }
		//
		// connection.rollback();
		// JOptionPane.showMessageDialog(this, "Transaction Rolled back",
		// "Information", JOptionPane.INFORMATION_MESSAGE);
		// } catch (SQLException ex) {
		// JOptionPane.showMessageDialog(this, ex.getMessage());
		// }

	}

	/**
	 * @param string
	 */
	public void setConncetionKey(String string) {
		conncetionKey = string;
	}

	/**
	 * @param string
	 */
	public void setConnectionName(String string) {
		connectionName = string;
	}

	public void setMyTableWidth() {
		int tableWidth = 0;
		FontMetrics metrics = table.getFontMetrics(table.getFont());
		for (int i = 0; i < table.getColumnCount(); ++i) {
			int width = 0;
			int maxWidth = 0;
			Vector<String> data = new Vector<String>();
			data.addElement(table.getColumnName(i));
			for (int j = 0; j < table.getRowCount(); ++j) {
				if (table.getValueAt(j, i) == null) {
					data.addElement(" ");
				} else {
					data.addElement(table.getValueAt(j, i).toString());
				}
			}
			Enumeration<String> enumeration = data.elements();
			while (enumeration.hasMoreElements()) {
				if ((width = metrics.stringWidth((String) enumeration
						.nextElement())) > maxWidth) {
					maxWidth = width + 30;
				}
			}
			Insets insets = ((JComponent) table.getCellRenderer(0, i))
					.getInsets();
			maxWidth += insets.left + insets.right;
			table.getColumnModel().getColumn(i).setPreferredWidth(maxWidth);
			tableWidth += maxWidth;
		}
		Dimension d = table.getSize();
		d.width = tableWidth;
		table.setSize(d);
		table.setCellSelectionEnabled(true);

	}

	public void setSqlTextArea(String s) {
		sqlTextArea.setText(s);
	}

	public void updateSQL(String query) {

		// int rowsHandled;
		//
		// doHistory(query);
		//
		// if (query == null) // If there's nothing we are done
		// return;
		// try {
		//
		// long startTime = System.currentTimeMillis();
		// rowsHandled = statement.executeUpdate(query);
		// model.setResultSet(null);
		// float qTime = System.currentTimeMillis() - startTime;
		// qTime = qTime / 1000;
		// query = query.trim();
		//
		// statusBar.elapsedTimePane.setVisible(true);
		// statusBar.messagePane.setVisible(true);
		//
		// if (query.toUpperCase().startsWith("INSERT")) {
		// statusBar.setElapsedTimePane(qTime + " Sec.");
		// statusBar.setMessagePane(rowsHandled + " row(s) inserted.");
		// } else if (query.toUpperCase().startsWith("UPDATE")) {
		// statusBar.setElapsedTimePane(qTime + " Sec.");
		// statusBar.setMessagePane(rowsHandled + " row(s) updated.");
		// } else if (query.toUpperCase().startsWith("DELETE")) {
		// statusBar.setElapsedTimePane(qTime + " Sec.");
		// statusBar.setMessagePane(rowsHandled + " row(s) deleted.");
		// } else {
		// statusBar.setElapsedTimePane(qTime + " Sec.");
		// statusBar.setMessagePane("Executed successfully ");
		// }
		// } catch (SQLException sqle) {
		// JOptionPane.showMessageDialog(this, sqle.getMessage());
		// statusBar.messagePane.setVisible(true);
		// statusBar.setMessagePane(sqle.getMessage()); // Display error
		// // message
		// }
	}

//	public ConnectionInformation getConnectionInformation() {
//		return (ConnectionInformation) mainFrame.getConnectionList().get(
//				conncetionKey);
//	}
	
	public ConnectionInformation getConnectionInformation() {
		return argConnectionDialog.getConnectionInformation();
	}

//	public void setKeywords(Vector<?> argKeywords) {
//		Document tmpDocument = sqlTextArea.getDocument();
//		if (tmpDocument != null && tmpDocument instanceof CodeDocument) {
//			((CodeDocument) tmpDocument).setKeywords(argKeywords);
//		}
//	}

	public void featureNotAvailable(String argfeatureName, String argDialect,
			Component argComponent) {
		Object tmp[] = { argfeatureName, argDialect };
		String msg = MessageFormat.format(
				"The {0} feature is not available for database dialect {1}.",
				tmp);
		JOptionPane.showMessageDialog(argComponent, msg,
				"Feature Not Available", JOptionPane.INFORMATION_MESSAGE);
	}

	public void undoLastEdit() {
		try {
			if (undo.canUndo()) {
				undo.undo();
			}
		} catch (CannotUndoException e) {
		}
	}

	public void redoLastEdit() {
		try {
			if (undo.canRedo()) {
				undo.redo();
			}
		} catch (CannotRedoException e) {
		}
	}

	/**
	 * @return Returns the frameIndex.
	 */
	public int getFrameIndex() {
		return frameIndex;
	}

	/**
	 * @param frameIndex
	 *            The frameIndex to set.
	 */
	public void setFrameIndex(int frameIndex) {
		this.frameIndex = frameIndex;
	}

	private void doHistory(String argQuery) {
		// Check to see if this is the first sql run.
		if (index_of_sqls != 0) {
			int historyMode = mainFrame.getConfig().getHistoryMode();
			if (historyMode == Config.HISTORY_MODE_UNIQUE) {
				// See if this query is already in the history
				int size = sqls.size();
				for (int x = 0; x < size; x++) {
					if (((String) sqls.get(x)).equals(argQuery)) {
						// if already in history do not add it again.
						return;
					}

				}
			} else if (historyMode == Config.HISTORY_MODE_DIFF_FROM_LAST) {
				if (((String) sqls.get(index_of_sqls - 1)).equals(argQuery)) {
					return;
				}
			}
		}
		if (this.index_of_sqls == 29) {
			sqls.remove(0);
			sqls.add((index_of_sqls - 1), argQuery);
		} else {
			sqls.add(index_of_sqls, argQuery);
			this.index_of_sqls++;
		}
		this.local_index_of_sqls = this.index_of_sqls - 1;
	}
}
